"""@package dfa


"""

import core

def write_dot(dfa):
	str = ""
	str += "digraph %s {\n" % (dfa.name)
	str += "\tgraph [nodesep=3.0, \n"
	str += "\tfontname=Arial, size=\"5, 5\", center=true]\n"
	str += "\tnode [shape=plaintext, fontsize=10, fixedsize=true]\n"
	str += "\tedge [arrowsize=1.0, arrowtail=none]\n"
	for state_name in dfa.states:
		state = dfa.states[state_name]
		for _in in state.transitions:
			t = state.transitions[_in]
			str += "\t%s -> %s [label=\"%s/%s\", fontsize=10]\n" \
				% (t.start.name, t.end.name, t._in, t._out)
	str += "}"
	return str

def write(dfa):
	str = ""
	str += "%s %s {\n" % (dfa.type, dfa.name)
	str += "\tinit = %s\n" % (dfa.init_state.name)
	for name in dfa.states:
		state = dfa.states[name]
		str += "\t%s: " % (name)
		for _in in state.transitions:
			t = state.transitions[_in]
			str += "%s/%s -> %s, " % (t._in, t._out, t.end.name)
		str += "\n"
	str += "}"
	return str

def read(input):
	lines = input.split("\n")
	del lines[-1] # peel off the last close brace

	# handle the first line, declaring DFA type and name
	line = lines.pop(0).split(" ")
	dfa = core.DFA(type=line[0], name=line[1])

	# get the initial state's name
	line = lines.pop(0).split(" ")
	init_name = line[-1]

	# iterate through each line from now on to set the transitions for 
	# each state

	states = []
	transitions = []
	for line in lines:
		line = line.lstrip("\t").rstrip(",")
		colon_index = line.index(":")
		state = line[: colon_index]
		states.append(state)
		
		trans = line[colon_index + 1:].split(",")
		for t in trans:
			parts = t.lstrip(" ").split(" ")
			bits = parts[0].split("/")
			transitions.append((state, parts[-1], bits[0], bits[1]))

	# now that we've gathered them all, we can actually add them to the
	# DFA
	for state in states:
		dfa.add_state(state)
	for trans in transitions:
		dfa.add_transition(trans[0], trans[1], trans[2], trans[3])

	# set the initial state
	dfa.set_init(init_name)

	print write(dfa)

